#include "Stopwatch.hh"

ResultOf Stopwatch::start()
{
	Started = false;
	Stoped = false;
	
	ResultOf Result;
	Result = gettimeofday(&StartTime, NULL);
	checkErrorWR(Result, "Fail gettimeofday.");
	
	Started = true;
	return RETURN_OK;
}

ResultOf Stopwatch::stop()
{
	if (!Started)
	{
		notifyError(Started, "start function is not called.");
		return RETURN_ERROR;
	}
	
	Stoped = false;
	
	ResultOf Result;
	Result = gettimeofday(&StopTime, NULL);
	checkErrorWR(Result, "Fail gettimeofday.");
	
	Stoped = true;
	
	return RETURN_OK;
}

USNumber Stopwatch::tellSec()
{
	if (!Started || !Stoped)
	{
		notifyError(0, "start/stop function is not called.");
		return 0;
	}
	
	return (Number)StopTime.tv_sec - (Number)StartTime.tv_sec;
}

USNumber Stopwatch::tellMicroSec()
{
	if (!Started || !Stoped)
	{
		notifyError(0, "start/stop function is not called.");
		return 0;
	}
	
	Number Sec;
	Sec = (Number)StopTime.tv_sec - (Number)StartTime.tv_sec;
	
	Number MicroSec;
	MicroSec = (Number)StopTime.tv_usec - (Number)StartTime.tv_usec;
	MicroSec += convertSec2uSec(Sec);
	
	return (USNumber)(MicroSec >= 0) ? MicroSec : 0;
}

USNumber Stopwatch::convertSec2uSec(USNumber Sec)
{
	return Sec * 1000000;
}

